<template>
  <page-header-wrapper :title="false">
    <a-card title="供应商&经销商详情">
      <template #extra> <a-button type="primary" @click="handleEdit(info)">编辑供应商&经销商</a-button></template>
      <a-descriptions bordered title="" size="small">
        <a-descriptions-item label="名称" :span="3"> {{ info?.name }} </a-descriptions-item>
        <a-descriptions-item label="类型" :span="3">  {{ info?.types === '1' ? '供应商': info?.types === '3' ? '供应商&经销商' : '经销商' }} </a-descriptions-item>
        <a-descriptions-item label="状态" :span="3">
          <a-tag color="#82af6f" v-if="info?.status == 1">合作中</a-tag>
          <a-tag color="#abbac3" v-else>停止合作</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="省" :span="3" v-if="info?.types !== '1'"> {{ info?.province }} </a-descriptions-item>
        <a-descriptions-item label="市" :span="3" v-if="info?.types !== '1'"> {{ info?.city }} </a-descriptions-item>
        <a-descriptions-item label="业务负责人" :span="3" v-if="info?.types !== '1'"> {{ info?.empName }} </a-descriptions-item>
        <a-descriptions-item label="区域" :span="3" v-if="info?.types !== '1'"> {{ info?.areaName }} </a-descriptions-item>
        <a-descriptions-item label="启用账期" :span="3" v-if="info?.types !== '1'"> {{ info?.accountDates ? '是' : '否' }} </a-descriptions-item>
        <a-descriptions-item label="账期额度" :span="3" v-if="info?.types !== '1' && info.accountDates"> {{ info?.accountQuota }} </a-descriptions-item>
        <a-descriptions-item label="账期天数" :span="3" v-if="info?.types !== '1' && info.accountDates"> {{ info?.accountDates }} </a-descriptions-item>
        <a-descriptions-item label="备注" :span="3"> {{ info?.memo }} </a-descriptions-item>
      </a-descriptions>
    </a-card>
    <a-card title="账户列表" style="margin-top: 24px">
      <template #extra>
        <a-tooltip>
          <template #title> 数据导出</template>
          <a-button type="primary" icon="database" @click="handleExpert(queryParam)"></a-button>
        </a-tooltip>
      </template>
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="筛选">
                <a-input v-model="queryParam.keyword" placeholder="请输入筛选" />
              </a-form-item>
            </a-col>
            <a-col :md="(!advanced && 8) || 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" :loading="loading" @click="handleSearch(queryParam)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (queryParam = {})">重置</a-button>
                <!-- <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a> -->
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <!-- <div class="table-operator">
        <a-button icon="cloud-upload">导出</a-button>
      </div> -->

      <a-table 
        ref="table" 
        size="default" 
        rowKey="key" 
        :columns="columns"         
        :data-source="loadData"
        :pagination="pagination"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="status" slot-scope="text, record">
          <template>
            <a-tag color="#abbac3" v-if="record?.accountType == '0'">待上账</a-tag>
            <a-tag color="#82af6f" v-if="record?.accountType == '1'">已上账</a-tag>
          </template>
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a-tag color="#428bca" @click="handleGroupEdit(record)">编辑</a-tag>
            <a-tag color="#428bca" @click="handleDetail(record)">详情</a-tag>
          </template>
        </span>
      </a-table>
    </a-card>
    <create-form
      ref="createModal"
      :visible="visible"
      :loading="confirmLoading"
      :model="mdl"
      @cancel="handleCancel"
      @ok="handleOk"
    />
    <group-form
      ref="createModal"
      :visible="groupVisible"
      :loading="groupLoading" 
      :model="mdll"
      @cancel="handleGroupCancel"
      @ok="handleGroupOk"
    />
  </page-header-wrapper>
</template>

<script>
import CreateForm from './edit'
import GroupForm from './groupForm'
import { getSuppliesUsingGET, getSuppliesAccountListUsingPOST,updateSuppliesUsingPOST,exportSpAccListUsingPOST } from '@/api/api/jingxiaoshangyunyingshangguanli.ts'
export default {
  name: 'AgentDetail',
  components: {
    CreateForm,
    GroupForm,
  },
  data() {
    return {
      info: {},
      queryParam: {
        pageNo:1,
        pageSize:10,
        queryCondition:'',
        status:''
      },
      advanced: false,
      mdll: null,
      mdl: null,
      visible: false,
      groupVisible: false,
      groupLoading: false,
      value: '',
      confirmLoading: false,
      loading: false,
      columns: [
        {
          title: '类型',
          dataIndex: 'status',
          needTotal: true,
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '结余(元)',
          dataIndex: 'curAmount',
        },
        {
          title: '初始(元)',
          dataIndex: 'startAmount',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      loadData: [],
      pagination: {},
    }
  },
  mounted() {
    this.getDetail()
    this.handleSearch(this.queryParam)
  },
  methods: {
    handleExpert(params){
      exportSpAccListUsingPOST({ ...params, supplyId: this.$route.params.id}).then((res) => {
          const blob = new Blob([res], {
            type: 'application/vnd.ms-excel;charset=utf-8',
          })
          const filename = '供应商&经销商账户列表' + '.xlsx'
          // 将blob对象转为一个URL
          var blobURL = window.URL.createObjectURL(blob)
          // 创建一个a标签
          var tempLink = document.createElement('a')
          // 隐藏a标签
          tempLink.style.display = 'none'
          // 设置a标签的href属性为blob对象转化的URL
          tempLink.href = blobURL
          // 给a标签添加下载属性
          tempLink.setAttribute('download', filename)
          if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank')
          }
          // 将a标签添加到body当中
          document.body.appendChild(tempLink)
          // 启动下载
          tempLink.click()
          // 下载完毕删除a标签
          document.body.removeChild(tempLink)
          window.URL.revokeObjectURL(blobURL)
          this.$message.success('导出成功~')
        })  
    },
    getDetail() {
      getSuppliesUsingGET({ id: this.$route.params.id })
        .then((res) => {
          this.info = res.data
        })
        .catch(() => {
          this.$message.error('获取详情失败,请联系管理员')
        })
    },
    handleSearch(params) {
      this.loading = true
      getSuppliesAccountListUsingPOST({...params, supplyId: this.$route.params.id})
        .then((res) => {
          this.loadData = res.data.list
          this.loading = false
          this.pagination = { ...this.pagination, total: Number(res.data.total) }
        })
        .catch(() => {
          this.loading = false
          this.$message.error('获取账户列表失败,请联系管理员')
        })
    },
    handleGroup() {
      this.groupVisible = true
    },
    handleEdit(record) {
      this.mdl = { ...record }
      this.visible = true
    },
    handleGroupEdit(record) {
      this.mdl = { ...record }
      this.groupVisible = true
    },
    handleDetail(record) {
      this.$router.push({ path: `/agent/account/${record?.id}`,query:{types:this.info.types} })
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          if (!!values.id) {
            // 修改 e.g.
            updateSuppliesUsingPOST({...values}).then(() => { 
              this.getDetail()
              this.$message.success('操作成功')
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
            })
            .catch((error) => {
              this.confirmLoading = false
              this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleGroupOk() {
      this.groupVisible = false
      this.groupLoading = true
      setTimeout(() => {
        this.groupLoading = false
      }, 1000)
      this.$message.success('操作成功')
    },
    handleGroupCancel() {
      this.groupVisible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
  },
}
</script>
